package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;

import redis.clients.jedis.Jedis;
import utils.RedisUtil;
import utils.SmsUtil;

/**
 * Servlet implementation class SmsServlet
 */
public class SmsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String phone = request.getParameter("phone");
		if (phone==null || phone =="") {
			return;
		}
		
		//生成验证码
		String code = RandomStringUtils.randomNumeric(4);

		//存储到redis
		Jedis jedis = RedisUtil.getJedis();
		String ok = jedis.setex("register::"+phone, 300, code);
		RedisUtil.closeJedis(jedis);
		
		if (!"OK".equals(ok)&&null==ok) {
			response.getWriter().print("0");
			return;
		}
		
		//发短信
		String[] datas = {code,"5"};
		boolean result = SmsUtil.sendSms(phone, "1",datas);
		
		if (!result) {
			response.getWriter().print("0");
			return;
		}
		response.getWriter().print("1");
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
